/**
 * 
 */
package com.bridgetree.jubaocrm.ui.groups;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.LoginUtil;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.util.CommentReviews;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;
/**
 * @author wop
 * 复审记录
 */
public class GroupsFuShenActivity extends Activity {
	private final String TAG ="GroupsFuShenActivity";
	private Context mContext;
	private Projects mProjects;
	private String user_id =""; 
	private String token ="";
	private ArrayList<CommentReviews> mMmemberList;
	private GroupsFuShenAdapter mRuAdapter2;
	private ListView firstcategory2 = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_group_members);
		mContext =  this;
		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");

		TextView xm_bi_tv_title =(TextView)findViewById(R.id.xm_bi_tv_title);
		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("Projects");
			xm_bi_tv_title.setText("复审记录");
		}

		findViewById(R.id.xm_bi_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		firstcategory2 = (ListView)findViewById(R.id.groups_lv);
		if(mProjects!=null){
			getGroupsGongGao();
		}
	}

	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	/**
	 * 获取复审记录的数据1
	 * @param pageIndex
	 */
	private void getGroupsGongGao() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else {
			final ProgressDialog progressDialog = ProgressDialog.show(this,
					"网络数据", "...Loading...");
			//			http://crmsoap.woniuwo.cn/client?cid=5374bfaed5ac700e4ce8f60d&part=r&user_id=cd34350bb2844077bfbd4abe5ec56f99&token=15f4b0826dc841198c30088f4a7afd90&validation=gAJ9cQAoVQZsb2NhbGVxAVUFemhfQ05xAl&page=1
			String URL = Network.API_DOMAIN + "/client?cid=" + mProjects.getClient_id()+"&part=r&user_id=" + user_id
			+ "&token=" + token + "&validation=" + CRMUserBaseInfo.kValication+"&page=1";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
					Request.Method.GET, URL, null,
					new Response.Listener<JSONObject>() {
						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("获取复审记录的数据1 response=" + response);
							try {
								if (!response.isNull("comment_of_reviews")) {
									String data = response.getString("comment_of_reviews");
									if (data.equals("[]")) {
										Toast.makeText(mContext, "已经到最后了~",
												Toast.LENGTH_SHORT).show();
									} else {
										org.json.JSONArray jsonArr;
										jsonArr = response.getJSONArray("comment_of_reviews");
										if(mMmemberList==null){
											mMmemberList = new ArrayList<CommentReviews>();
										}
										if (jsonArr.length() > 0) {
											for (int i = 0; i < jsonArr
											.length(); i++) {
												CommentReviews mCommentReviews = new CommentReviews();
												JSONObject jsonObj2 = jsonArr
												.getJSONObject(i);
												if (!jsonObj2.isNull("comment")) {
													String comment = jsonObj2.getString("comment");
													mCommentReviews.setComment(comment);
												}
												if (!jsonObj2.isNull("created")) {
													String created = jsonObj2.getString("created");
													mCommentReviews.setCreated(created);
												}
												if (!jsonObj2.isNull("fullname")) {
													String fullname = jsonObj2.getString("fullname");
													mCommentReviews.setFullname(fullname);
												}
												mMmemberList.add(mCommentReviews);
											}
										}
										mRuAdapter2 = new GroupsFuShenAdapter(mContext, mMmemberList);
										firstcategory2.setAdapter(mRuAdapter2);
									}
								}
								if (!response.isNull("errors")) {
									String errors = response.get("errors")
									.toString();
									if (errors.equals("[]")) {
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
											.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
												.length(); i++) {
													JSONObject jsonObj2 = jsonArr
													.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
														.getString("desc");
														mLoginError
														.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
														.getString("value");
														mLoginError
														.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (NumberFormatException e) {
								e.printStackTrace();
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError arg0) {
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");
						}
					});
			requestQueue.add(jsonObjectRequest);
		}
	}

}

class GroupsFuShenAdapter extends BaseAdapter {

	private List<CommentReviews> DrugstoreDataList = null;
	private LayoutInflater listContainer; // 视图容器

	public final class ListItemView { // 自定义控件集合
		public TextView xm_ai_item_tv_name;
		public TextView xm_ai_item_tv_time;
		public TextView xm_ai_item_tv_content;
	}

	public GroupsFuShenAdapter(Context mContext,
			List<CommentReviews> mCommentReviews) {
		this.DrugstoreDataList = mCommentReviews;
		listContainer = (LayoutInflater) mContext
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	@Override
	public int getCount() {
		if (DrugstoreDataList != null) {
			return DrugstoreDataList.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return DrugstoreDataList.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ListItemView listItemView = null;
		if (convertView == null) {
			listItemView = new ListItemView();
			// 获取list_item布局文件的视图
			convertView = listContainer.inflate(R.layout.xm_approval_information_item, null);
			// 获取控件对象
			listItemView.xm_ai_item_tv_name = (TextView) convertView.findViewById(R.id.xm_ai_item_tv_name);
			listItemView.xm_ai_item_tv_time = (TextView) convertView.findViewById(R.id.xm_ai_item_tv_time);
			listItemView.xm_ai_item_tv_content = (TextView) convertView.findViewById(R.id.xm_ai_item_tv_content);
			// 设置控件集到convertView
			convertView.setTag(listItemView);
		} else {
			listItemView = (ListItemView) convertView.getTag();
		}
		
		listItemView.xm_ai_item_tv_name.setText((String) DrugstoreDataList.get(position).getFullname());
		listItemView.xm_ai_item_tv_time.setText((String) DrugstoreDataList.get(position).getCreated());
		listItemView.xm_ai_item_tv_content.setText((String) DrugstoreDataList.get(position).getComment());
		// listItemView.RelativeLayout_drugstorelist.setOnClickListener(new
		// OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // TODO Auto-generated method stub
		// mContext.startActivity(new Intent(mContext,
		// DrugStoreDetailsActivity.class));
		// }
		// });
		return convertView;
	}

}
